//
//  FunitureShopViewController.m
//  FKGW
//
//  Created by song ce on 2017/2/24.
//  Copyright © 2017年 song ce. All rights reserved.
//

#import "FunitureShopViewController.h"
#import "StoreCollectionV.h"
#import "ScanAllViewController.h"
#import "YBPopupMenu.h"
#import "UIViewController+MMDrawerController.h"
#import "ProductModel.h"
#define TITLES @[@"综合排序", @"价格由高到低", @"价格由低到高"]

#define KpageCount   @"10"    //每页数据量
@interface FunitureShopViewController ()<YBPopupMenuDelegate>

@property (weak, nonatomic) IBOutlet UIButton *firstButton;
@property (weak, nonatomic) IBOutlet UIButton *middleButton;
@property (weak, nonatomic) IBOutlet UIButton *rightButton;
@property (weak, nonatomic) IBOutlet UIView *buttonView;
@property(nonatomic,strong)YBPopupMenu *popupMenu;
@property (weak, nonatomic) IBOutlet UIView *bottomV;

@property(nonatomic,strong)StoreCollectionV *storeCollectionV;
@property(nonatomic,strong)NSMutableArray *dataSource;

@property(nonatomic,assign)BOOL isSelectedLongText;

@property(nonatomic,strong)NSMutableArray *typeArray;
@property(nonatomic,assign)NSInteger currentSortType;
@property(nonatomic,copy)NSString *parameterData;
@property(nonatomic,strong)NSDictionary *paramDic;

//下拉刷新相关
@property(nonatomic,assign)NSInteger arrCount;//用于判断上拉加载更多是否有
@property(nonatomic,assign)int indeex;

@end

@implementation FunitureShopViewController
-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //1.我们需要拿到MMDraw控制器（1：将其设置为appdelegate的属性；2，它提供了一个类目，我们就使用这个类目）
    MMDrawerController *mmdraw =  [self mm_drawerController];
    [mmdraw setOpenDrawerGestureModeMask:MMOpenDrawerGestureModeAll];
    [mmdraw setCloseDrawerGestureModeMask:MMCloseDrawerGestureModeAll];
    //然后在视图将要消失的时候改变回来
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    MMDrawerController *mmdraw =  [self mm_drawerController];
    [mmdraw setOpenDrawerGestureModeMask:MMOpenDrawerGestureModeNone];
    [mmdraw setCloseDrawerGestureModeMask:MMCloseDrawerGestureModeNone];
        [_popupMenu dismiss];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    if(!ISNOTNEEDMESSAGEBTN){
        self.isNeedMessageItem = YES;
    }
    self.currentSortType = 0;
    self.parameterData = @"";
    self.typeArray = [NSMutableArray array];
    for(int i=0;i<TITLES.count;i++){
        ProductModel *pmodel = [[ProductModel alloc]init];
        pmodel.name = TITLES[i];
        [self.typeArray addObject:pmodel];
    }

     self.dataSource = [NSMutableArray array];
    StoreCollectionV *storeCollectionV = [[StoreCollectionV alloc]initWithFrame:CGRectMake(0, 0, Main_Screen_Width, Main_Screen_Height-104)];
    storeCollectionV.isScrollEnabled = YES;
    
    [self.bottomV addSubview:storeCollectionV];
    _storeCollectionV = storeCollectionV;
//    [self searchButton];
    //接收到筛选页面点击完成的通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refrshData:) name:@"complete" object:nil];
    
    [self.firstButton setTitle:@"综合排序" forState:UIControlStateNormal];
    if(Main_Screen_Width==320){//4s  5  5s
           [self.firstButton setImageEdgeInsets:UIEdgeInsetsMake(0, 70, 0, 0)];
    }else if(Main_Screen_Width==375){//6 6s 7
       [self.firstButton setImageEdgeInsets:UIEdgeInsetsMake(0, 70, 0, 0)];
    }else if(Main_Screen_Width==414){//6plus  7plus
      [self.firstButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 5, 0, 0)];
       [self.firstButton setImageEdgeInsets:UIEdgeInsetsMake(0, 105, 0, 0)];
    }
    DLog(@"%f",Main_Screen_Width);
    [self  loadData];
//    [self loadMoreData];
}

#pragma mark - 加载更多数据
- (void)loadMoreData{
    __weak typeof(self) weakSelf = self;
    self.indeex = 1;
    //上拉加载更多
    self.storeCollectionV.collectionV.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        if(weakSelf.arrCount<[KpageCount intValue]){
            [weakSelf.storeCollectionV.collectionV.mj_footer setState:MJRefreshStateNoMoreData];
        }else{
            self.indeex ++;
            NSString *page = [NSString stringWithFormat:@"%d",self.indeex];
            //参数2 代表操作的是上拉加载更多
            [weakSelf loadDataWithIndex:2 withPage:page];
        }
    }];
    
    //下拉刷新
    self.storeCollectionV.collectionV.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.indeex = 1;
        [weakSelf loadDataWithIndex:1 withPage:@"1"];
    }];
}

-(void)loadData{
    [self loadDataWithIndex:0 withPage:@"1"];
}
- (void)loadDataWithIndex:(int)index withPage:(NSString*)page{
    if(!USERID.length){
        USERID = @"";
    }
   //2.21筛选界面执行筛选接口
    NSString *sortType = [NSString stringWithFormat:@"%ld",self.currentSortType];
    NSDictionary *paramDic = @{
                               @"productTypeId":self.productTypeId,
                               @"sortType":sortType,
                               @"currentPage":page,
                               @"size":KpageCount,
                               @"parameterData":self.parameterData,
                               @"userId":USERID
                               };
    self.paramDic = paramDic;
    DLog(@"--执行筛选的参数--%@",paramDic);
    __weak typeof(self)  weakSelf = self;
    if(index==0){
         [MBProgressHUD showLoadingGif];
    }
    [Tools AFNetworkingRequestTypePostWithUrl:DOSREEN paramters:paramDic afterResultBlock:^(NSDictionary *resultDic) {
        DLog(@"根据产品类别查询所有商品----%@",resultDic);
        if([resultDic[@"flag"] isEqualToString:@"true"]){
            NSDictionary *dataDic = resultDic[@"data"];
            if([dataDic isKindOfClass:[NSNull class]]) {
                [MBProgressHUD dismissHUD];
                return ;
            }
            //商品内容
            NSArray *data = dataDic[@"products"];
            NSMutableArray *startEndArr = [NSMutableArray array];
            for(NSDictionary *dic in data){
                StoreModel *model = [[StoreModel alloc]init];
                model.imageName = dic[@"productPic"];
                model.goodsName = dic[@"productName"];
                model.price = [NSString stringWithFormat:@"%@",dic[@"price"]];
                model.id = dic[@"productId"];
                if(data.count&&startEndArr.count>data.count-3){
                    model.isNotNeedBottomLine= YES;
                }
                if(data.count<3){
                    model.isNotNeedBottomLine= YES;
                }
                [startEndArr addObject:model];
            }
            if(index==2){
                if(weakSelf.dataSource.count&&data.count){
                    StoreModel *model1 = weakSelf.dataSource.lastObject;
                    model1.isNotNeedBottomLine = NO;
                    StoreModel *model2 = weakSelf.dataSource[weakSelf.dataSource.count-2];
                    model2.isNotNeedBottomLine = NO;
                }
            }else{
                if(weakSelf.dataSource.count){
                    [weakSelf.dataSource removeAllObjects];
                }
            }
            [weakSelf.dataSource addObjectsFromArray:startEndArr];
            weakSelf.arrCount = startEndArr.count;
            if(!weakSelf.dataSource.count){
                [weakSelf.view addSubview:weakSelf.noDataIUmageV];
            }else{
                [weakSelf.noDataIUmageV removeFromSuperview];
            }
            weakSelf.storeCollectionV.dataSoure = weakSelf.dataSource;
            if(index==0){
                if(startEndArr.count==[KpageCount integerValue]){
                    //加载更多数据
                    [self loadMoreData];
                }else{
                    weakSelf.storeCollectionV.collectionV.mj_header = nil;
                    weakSelf.storeCollectionV.collectionV.mj_footer = nil;
                }
                [MBProgressHUD dismissHUD];
            }
            if([weakSelf.storeCollectionV.collectionV.mj_header isRefreshing]){
                [weakSelf.storeCollectionV.collectionV.mj_header endRefreshing];
            }
            if([weakSelf.storeCollectionV.collectionV.mj_footer isRefreshing]){
                [weakSelf.storeCollectionV.collectionV.mj_footer endRefreshing];
            }
            if(weakSelf.arrCount<[KpageCount intValue]){
                [weakSelf.storeCollectionV.collectionV.mj_footer setState:MJRefreshStateNoMoreData];
            }

        }else{
             [MBProgressHUD showLoadingGif];
            if(resultDic[@"errorString"]){
                [MBProgressHUD showTipMessageInWindow:resultDic[@"errorString"]];
            }
        }
    }];
}

//2.21筛选界面执行筛选接口
-(void)refrshData:(NSNotification*)noti{
    self.parameterData = noti.object;
    //1，关闭筛选页面
    [self closeMMDrawer];
    [self loadData];
}

-(void)closeMMDrawer{
    MMDrawerController *mmdraw =  [self mm_drawerController];
//    [mmdraw openDrawerSide:MMDrawerSideRight animated:YES completion:nil];
    [mmdraw closeDrawerAnimated:YES completion:nil];
}

-(void)searchButton{
    if(!ISNOTNEEDMESSAGEBTN){
        self.isNeedMessageItem = YES;
    }

    
    UIButton *locationButton2 = [UIButton buttonWithType:UIButtonTypeCustom];
    locationButton2.frame=CGRectMake(0, 0, 40, 40);
    [locationButton2 setImage:[UIImage imageNamed:@"nav_icon_sousuo_nor"] forState:UIControlStateNormal];
    [locationButton2 addTarget:self action:@selector(right2Action) forControlEvents:UIControlEventTouchUpInside];
    self.rightItem2 = locationButton2;
}

//信息
-(void)right1Action{
    
    
    
}
//搜索
-(void)right2Action{
    
    
    
}
//综合排序
- (IBAction)firstAAction:(UIButton *)sender {
    sender.selected = !sender.selected;
    if(sender.isSelected){
        _popupMenu = [YBPopupMenu  showAtPoint:CGPointMake(0, self.buttonView.bottom) titles:self.typeArray icons:nil menuWidth:120 view:self.view delegate:self];
        _popupMenu.backGroudColor = [UIColor whiteColor];
        _popupMenu.isShowSeparator = YES;
        _popupMenu.text_Color = [UIColor blackColor];
        _popupMenu.seperaterColor = [UIColor colorWithRed:234./255 green:234./255 blue:234./255 alpha:1.];
        [sender setImage:[UIImage imageNamed:@"icon_up"] forState:UIControlStateSelected];
    }else{
        [_popupMenu dismiss];
        [sender setImage:[UIImage imageNamed:@"icon_down"] forState:UIControlStateNormal];
    }
}

#pragma mark - YBPopupMenuDelegate
- (void)ybPopupMenuDidSelectedAtIndex:(NSInteger)index ybPopupMenu:(YBPopupMenu *)ybPopupMenu
{
     ProductModel *model = _typeArray[index];
    self.currentSortType = index;
    [self.firstButton setTitle:model.name forState:UIControlStateNormal];
    if(Main_Screen_Width==320){//4s  5  5s
        if(self.firstButton.currentTitle.length==6){
             self.isSelectedLongText = YES;
            [self.firstButton setTitleEdgeInsets:UIEdgeInsetsMake(0, -18, 0, 0)];
            [self.firstButton setImageEdgeInsets:UIEdgeInsetsMake(0, 97, 0, 0)];
        }else{
            if(self.isSelectedLongText){
                [self.firstButton setImageEdgeInsets:UIEdgeInsetsMake(0, 85, 0, 0)];
            }else{
                [self.firstButton setImageEdgeInsets:UIEdgeInsetsMake(0, 70, 0, 0)];
            }
        }
    }else if(Main_Screen_Width==375){//6 6s 7
        if(self.firstButton.currentTitle.length==6){
            self.isSelectedLongText = YES;
            [self.firstButton setTitleEdgeInsets:UIEdgeInsetsMake(0, -10, 0, 0)];
            [self.firstButton setImageEdgeInsets:UIEdgeInsetsMake(0, 113, 0, 0)];
        }else{
            if(self.isSelectedLongText){
              [self.firstButton setImageEdgeInsets:UIEdgeInsetsMake(0, 93, 0, 0)];
            }else{
               [self.firstButton setImageEdgeInsets:UIEdgeInsetsMake(0, 73, 0, 0)];
            }
        }
    }else if(Main_Screen_Width==414){//6plus  7plus
        if(self.firstButton.currentTitle.length==6){
             self.isSelectedLongText = YES;
            [self.firstButton setTitleEdgeInsets:UIEdgeInsetsMake(0, -10, 0, 0)];
            [self.firstButton setImageEdgeInsets:UIEdgeInsetsMake(0, 118, 0, 0)];
        }else{
            if(self.isSelectedLongText){
                  [self.firstButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 5, 0, 0)];
                [self.firstButton setImageEdgeInsets:UIEdgeInsetsMake(0, 110, 0, 0)];
            }else{
                [self.firstButton setImageEdgeInsets:UIEdgeInsetsMake(0, 105, 0, 0)];
            }
        }
    }
        [self firstAAction:self.firstButton];
    [_popupMenu dismiss];
    DLog(@"点击了 %@ 选项",model.name);
    //加载数据
    [self loadData];
}


//快速查看
- (IBAction)middleAction:(UIButton *)sender {
    ScanAllViewController *scanAllCtrl = [[ScanAllViewController alloc]init];
    scanAllCtrl.count = 2;
    scanAllCtrl.isModel = YES;
    scanAllCtrl.paramDic = self.paramDic;
    BaseNavigationViewController *navi = [[BaseNavigationViewController alloc]initWithRootViewController:scanAllCtrl];
    [self   presentViewController:navi animated:YES completion:nil];

}

//筛选
- (IBAction)rightButton:(UIButton *)sender {
     MMDrawerController *mmdraw =  [self mm_drawerController];
     [mmdraw openDrawerSide:MMDrawerSideRight animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
